// 字典库 sys_dictionary sys_dictionary_data
const db = require('../db')
const { getNowTime, formatTime } = require('../utils/index')

/**
 * 新增字典
 * @param {*} req
 * @param {*} res
 */
exports.addDictionary = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_dictionary where is_delete = 0 and (code = ? or name = ?)`
  db.query(selectSql, [req.body.code, req.body.name], (err, results) => {
    if (err) return res.new_send(err)
    // 判断字典名称和字典编码是否存在
    if (results.length >= 2) return res.new_send('字典名称与字典编码已存在')
    if (results.length === 1) {
      const { code, name } = results[0]
      const { code: menu_code, name: menu_name } = req.body
      if (code === menu_code && name === menu_name) {
        return res.new_send('字典名称与字典编码已存在')
      }
      if (name === menu_name) {
        return res.new_send('字典名称已存在')
      }
      if (code === menu_code) {
        return res.new_send('字典编码已存在')
      }
    }
    // 插入数据库
    const insertSql = `insert into sys_dictionary set ?`
    db.query(insertSql, req.body, (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('新增字典目录失败')
      res.send({
        status: 0,
        message: '新增字典目录成功',
        data: { insertId: results.insertId }
      })
    })
  })
}

/**
 * 修改字典
 * @param {*} req
 * @param {*} res
 */
exports.updateDictionary = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_dictionary where id <> ? and is_delete = 0 and (code = ? or name = ?)`
  db.query(
    selectSql,
    [req.body.id, req.body.code, req.body.name],
    (err, results) => {
      if (err) return res.new_send(err)
      // 判断字典名称和字典编码是否存在
      if (results.length >= 2) return res.new_send('字典名称与字典编码已存在')
      if (results.length === 1) {
        const { code, name } = results[0]
        const { code: menu_code, name: menu_name } = req.body
        if (code === menu_code && name === menu_name) {
          return res.new_send('字典名称与字典编码已存在')
        }
        if (name === menu_name) {
          return res.new_send('字典名称已存在')
        }
        if (code === menu_code) {
          return res.new_send('字典编码已存在')
        }
      }

      //  修改数据库
      const updateSql = `update sys_dictionary set ? where Id = ?`
      db.query(updateSql, [req.body, req.body.id], (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows !== 1) return res.new_send('更新字典目录失败')
        res.new_send('更新字典目录成功', 0)
      })
    }
  )
}

/**
 * 删除字典
 * @param {*} req
 * @param {*} res
 */
exports.deleteDictionaryById = (req, res) => {
  // 存在明细
  const selectSql = `select * from sys_dictionary_data where dictionary_id = ?`
  db.query(selectSql, req.params.id, (err, results) => {
    if (results.length <= 0) {
      const deleteSql = `update sys_dictionary set is_delete = 1 where id = ?`
      db.query(deleteSql, req.params.id, (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows <= 0) return res.new_send('删除字典目录失败')
        res.new_send('删除字典目录成功', 0)
      })
    } else {
      res.new_send('此字典存在明细数据，不能删除')
    }
  })
}

/**
 * 获取字典列表
 * @param {*} req
 * @param {*} res
 */
exports.getDictionaryLsit = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  const selectSql = `select a.*, b.username user_name from sys_dictionary as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0 limit ?,?`
  db.query(selectSql, params, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    // 列表数据
    let dictionarys = results

    // 查询数据库总数
    const totalSql = `select count(*) as total from sys_dictionary where is_delete = 0`
    db.query(totalSql, (err, results) => {
      if (err) return res.new_send(err)
      let total = results[0]['total'] // 总数
      res.send({
        status: 0,
        message: '获取字典目录列表成功',
        page_num,
        page_size,
        total,
        data: dictionarys
      })
    })
  })
}

/**
 * 获取字典信息
 * @param {*} req
 * @param {*} res
 */
exports.getDictionaryById = (req, res) => {
  const selectSql = `select * from sys_dictionary where id = ?`
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    res.send({
      status: 0,
      message: '获取字典目录信息成功',
      data: results
    })
  })
}

/**
 * 新增字典数据
 * @param {*} req
 * @param {*} res
 */
exports.addDictionaryData = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_dictionary_data where is_delete = 0 and data_key = ? `
  db.query(selectSql, [req.body.data_key], (err, results) => {
    if (err) return res.new_send(err)
    if (results.length >= 1) {
      const { data_key } = results[0]
      const { data_key: dic_key } = req.body
      if (data_key === dic_key) {
        return res.new_send('字典数据名已存在')
      }
    }

    // 插入数据库
    const insertSql = `insert into sys_dictionary_data set ?`
    db.query(insertSql, req.body, (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('新增字典数据失败')
      res.send({
        status: 0,
        message: '新增字典数据成功',
        data: { insertId: results.insertId }
      })
    })
  })
}

/**
 * 修改字典数据
 * @param {*} req
 * @param {*} res
 */
exports.updateDictionaryData = (req, res) => {
  // 日期时间格式化
  req.body.create_time = req.body.create_time
    ? formatTime(req.body.create_time)
    : getNowTime()
  // 查询
  const selectSql = `select * from sys_dictionary_data where id <> ? and is_delete = 0 and data_key = ?`
  db.query(selectSql, [req.body.id, req.body.data_key], (err, results) => {
    if (err) return res.new_send(err)
    if (results.length === 1) {
      const { data_key } = results[0]
      const { data_key: dic_key } = req.body
      if (data_key === dic_key) {
        return res.new_send('字典数据名已存在')
      }
    }
    //  修改数据库
    const updateSql = `update sys_dictionary_data set ? where Id = ?`
    db.query(updateSql, [req.body, req.body.id], (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('更新字典数据失败')
      res.new_send('更新字典数据成功', 0)
    })
  })
}

/**
 * 删除字典数据
 * @param {*} req
 * @param {*} res
 */
exports.deleteDictionaryDataById = (req, res) => {
  const deleteSql = `update sys_dictionary_data set is_delete = 1 where id = ?`
  db.query(deleteSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows <= 0) return res.new_send('删除字典数据失败')
    res.new_send('删除字典数据成功', 0)
  })
}

/**
 * 获取字典数据列表
 * @param {*} req
 * @param {*} res
 */
exports.getDictionaryDataLsit = (req, res) => {
  // 分页加载
  const page_num = req.query.page_num || 1 //当前的num
  const page_size = req.query.page_size || 10 //当前页的数量
  const name = req.query.name
  const dictionary_id = req.query.dictionary_id
  const params = [
    (parseInt(page_num) - 1) * parseInt(page_size),
    parseInt(page_size)
  ]
  // 查询
  const selectSql =
    `select a.*, b.username user_name from sys_dictionary_data as a left join sys_user as b on a.user_id = b.id where a.is_delete = 0` +
    (name ? ` and a.data_value like '%${name}%'` : '') +
    (dictionary_id ? ` and a.dictionary_id = ${dictionary_id}` : '') +
    ` limit ?,?`
  db.query(selectSql, params, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    // 列表数据
    let datas = results

    // 查询数据库总数
    const totalSql =
      'select count(*) as total from sys_dictionary_data where is_delete = 0' +
      (name ? ` and data_value like '%${name}%'` : '') +
      (dictionary_id ? ` and dictionary_id = ${dictionary_id}` : '')
    db.query(totalSql, (err, results) => {
      if (err) return res.new_send(err)
      let total = results[0]['total'] // 总数
      res.send({
        status: 0,
        message: '获取字典数据列表成功',
        page_num,
        page_size,
        total,
        data: datas
      })
    })
  })
}

/**
 * 获取字典数据信息
 * @param {*} req
 * @param {*} res
 */
exports.getDictionaryDataById = (req, res) => {
  const selectSql = `select * from sys_dictionary_data where id = ?`
  db.query(selectSql, req.params.id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    res.send({
      status: 0,
      message: '获取字典数据信息成功',
      data: results
    })
  })
}
